import axios from 'axios'
import store from '../store'
import router from '../router'
import Config from '@/utils/config.js'
import Store2 from 'store2'
import { Message } from 'element-ui'
// import NProgress from 'nprogress'

let baseURL
switch (process.env.NODE_ENV) {
  case 'development':
    baseURL = Config.DEVELOPMENT_REQ_URL
    break
  case 'release':
    baseURL = Config.RELEASE_REQ_URL
    break
  case 'production':
    baseURL = Config.PRODUCTION_REQ_URL
    break
}

// 创建axios实例
const service = axios.create({
  baseURL, // api的base_url
  timeout: 6000
})

// request拦截器
service.interceptors.request.use(config => {
  // 配置config
  config.headers['X-APP-ID'] = Config.APP_ID
  config.headers['X-APP-VER'] = Config.APP_VER
  config.headers['Authorization'] = `Bearer ${store.getters.token || ''}`
  // 显示进度条
  // NProgress.start()
  return config
}, error => {
  console.log(error)
  return Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  (response) => {
    // 关闭进度条
    // NProgress.done()
    // 处理response
    let code = response.data.code
    let message = response.data.message
    switch (code) {
      case Config.SUCCESS_CODE:
        return response.data
      case Config.ERROR_CODE:
        Message.error(message)
        return Promise.reject(response.data)
      case Config.NOT_LOGGED:
        Store2.remove('userToken')
        store.dispatch('removeToken')
        store.dispatch('clearUserInfo')
        router.push({ name: 'login' })
        document.title = 'GMALL'
        return Promise.reject(response.data)
      case Config.LOGIN_INFO_ERR:
        Message.error(message)
        return Promise.reject(response.data)
      default:
        console.error(message)
        return Promise.reject(response.data)
    }
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
